package com.example.zbh.dsliao.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.util.EMLog;
import com.easemob.util.PathUtil;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.application.App;
import com.example.zbh.dsliao.ui.activty.LoginActivity;
import com.example.zbh.dsliao.ui.activty.MainActivity;
import com.example.zbh.dsliao.view.CustomChangeDialog;
import com.example.zbh.dsliao.view.CustomDialog;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;

/**
 * Created by zbh on 15/11/18.
 */
public class DliaoUtils {

    /*
    *
    * 检测网络是否可用
     */

    public static boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable() && mNetworkInfo.isConnected();
            }
        }

        return false;
    }

    /**
     * 根据汉字获取对应的拼音
     *
     * @param str
     * @return
     */
    public static String getPinyin(String str) {
        // 黑马 -> HEIMA
        // 设置输出配置
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        // 设置大写
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        // 设置不需要音调
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuilder sb = new StringBuilder();

        // 获取字符数组
        char[] charArray = str.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            char c = charArray[i];
            // 如果是空格, 跳过当前的循环
            if (Character.isWhitespace(c)) {
                continue;
            }

            if (c > 128 || c < -127) {
                // 可能是汉字
                try {
                    // 根据字符获取对应的拼音. 黑 -> HEI , 单 -> DAN , SHAN
                    String s = PinyinHelper.toHanyuPinyinStringArray(c, format)[0];
                    sb.append(s);

                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                // *&$^*@654654LHKHJ
                // 不需要转换, 直接添加
                sb.append(c);
            }
        }

        return sb.toString();
    }


    /**
     * 设置用户头像
     **/
    public static void setUserAvatar(Context context, String username, ImageView imageView) {


    }

    //得到图片地址
    public static String getImagePath(String remoteUrl) {
        String imageName = remoteUrl.substring(remoteUrl.lastIndexOf("/") + 1, remoteUrl.length());
        String path = PathUtil.getInstance().getImagePath() + "/" + imageName;
        EMLog.d("msg", "image path:" + path);
        return path;

    }
    //得到图片地址
    public static String getThumbnailImagePath(String thumbRemoteUrl) {
        String thumbImageName= thumbRemoteUrl.substring(thumbRemoteUrl.lastIndexOf("/") + 1, thumbRemoteUrl.length());
        String path =PathUtil.getInstance().getImagePath()+"/"+ "th"+thumbImageName;
        EMLog.d("msg", "thum image path:" + path);
        return path;
    }
    public static Bitmap decodeScaleImage(String var0, int var1, int var2) {
        BitmapFactory.Options var3 = getBitmapOptions(var0);
        int var4 = calculateInSampleSize(var3, var1, var2);
        EMLog.d("img", "original wid" + var3.outWidth + " original height:" + var3.outHeight + " sample:" + var4);
        var3.inSampleSize = var4;
        var3.inJustDecodeBounds = false;
        Bitmap var5 = BitmapFactory.decodeFile(var0, var3);
        int var6 = readPictureDegree(var0);
        Bitmap var7 = null;
        if(var5 != null && var6 != 0) {
            var7 = rotaingImageView(var6, var5);
            var5.recycle();
            var5 = null;
            return var7;
        } else {
            return var5;
        }
    }
    public static BitmapFactory.Options getBitmapOptions(String var0) {
        BitmapFactory.Options var1 = new BitmapFactory.Options();
        var1.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(var0, var1);
        return var1;
    }
    public static int calculateInSampleSize(BitmapFactory.Options var0, int var1, int var2) {
        int var3 = var0.outHeight;
        int var4 = var0.outWidth;
        int var5 = 1;
        if(var3 > var2 || var4 > var1) {
            int var6 = Math.round((float)var3 / (float)var2);
            int var7 = Math.round((float)var4 / (float)var1);
            var5 = var6 > var7?var6:var7;
        }

        return var5;
    }
    public static int readPictureDegree(String var0) {
        short var1 = 0;

        try {
            ExifInterface var2 = new ExifInterface(var0);
            int var3 = var2.getAttributeInt("Orientation", 1);
            switch(var3) {
                case 3:
                    var1 = 180;
                case 4:
                case 5:
                case 7:
                default:
                    break;
                case 6:
                    var1 = 90;
                    break;
                case 8:
                    var1 = 270;
            }
        } catch (IOException var4) {
            var4.printStackTrace();
        }

        return var1;
    }
    public static Bitmap rotaingImageView(int var0, Bitmap var1) {
        Matrix var2 = new Matrix();
        var2.postRotate((float)var0);
        Bitmap var3 = Bitmap.createBitmap(var1, 0, 0, var1.getWidth(), var1.getHeight(), var2, true);
        return var3;
    }

    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard() {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }
    public static List<Camera.Size> getResolutionList(Camera camera)
    {
        Camera.Parameters parameters = camera.getParameters();
        List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
        return previewSizes;
    }
    public static class ResolutionComparator implements Comparator<Camera.Size> {

        @Override
        public int compare(Camera.Size lhs, Camera.Size rhs) {
            if(lhs.height!=rhs.height)
                return lhs.height-rhs.height;
            else
                return lhs.width-rhs.width;
        }

    }




    /**
     * 账号其他设备登录
     * **/
    public static void showDialogConnection(final Context context) {
        final CustomChangeDialog dialog = new CustomChangeDialog(context, "您的账号已经在另一台设备上登录,您被迫下线", View.GONE, "", "换个账号登录", "不要怂,怼回去!");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeTwoBtn://换个账号登录
                        dialog.dismiss();
                        PreferenceHelper.getInstance().removeCurrentUserName();
                        PreferenceHelper.getInstance().removeCurrentUserPsw();
                        Intent intent = new Intent();
                        intent.setClass(context, LoginActivity.class);
                        //关闭到跳转到登录页面中间的所有activity
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent);
                        //再关闭当前页面 保证最后只有登录页面
                        android.os.Process.killProcess(android.os.Process.myPid());
                        break;
                    case R.id.cancleBtn://顶回来
                        dialog.dismiss();
                        final CustomDialog customDialog = new CustomDialog(context, "玩命顶回来...");
                        customDialog.show();
                        String username = PreferenceHelper.getInstance().getCurrentUserName();
                        String psw = PreferenceHelper.getInstance().getCurrentUserPsw();
                        if (username != null && psw != null){
                            EMChatManager.getInstance().login(username, psw, new EMCallBack() {
                                @Override
                                public void onSuccess() {
                                    customDialog.dismiss();
                                }
                                @Override
                                public void onError(int i, String s) {
                                }
                                @Override
                                public void onProgress(int i, String s) {
                                }
                            });
                        }else {
                            Toast.makeText(context, "怼不回去了.自己登录去吧", Toast.LENGTH_SHORT).show();
                            Intent intentl = new Intent();
                            intentl.setClass(context, LoginActivity.class);
                            //关闭到跳转到登录页面中间的所有activity
                            intentl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            context.startActivity(intentl);
                            //再关闭当前页面 保证最后只有登录页面
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }
                        break;
                }
            }
        });
    }


    /**
     * 账号被后台删除
     * **/
    public static void showDialogUserRemoved(final Context context) {
        final CustomChangeDialog dialog = new CustomChangeDialog(context, "您的账号在后台被移除了,请您切换账号登陆", View.GONE, "", "知道了", "取消");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeTwoBtn:
                        dialog.dismiss();
                        break;
                    case R.id.cancleBtn:
                        dialog.dismiss();
                        break;
                }
            }
        });

    }





}
